import router from "@/router";
import type { ResponseResult } from "@/stores/common";
import { usetoken } from "@/stores/token";
import axios, { AxiosError, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus";


const instance = axios.create({
  baseURL:import.meta.env.VUE_APP_BASE_URL,
  timeout:20000
})
// 请求拦截器
instance.interceptors.request.use((config:InternalAxiosRequestConfig)=> {
  // 注入token
  const store = usetoken()
  // 判断如果能获取到token则将这个值保存到请求头中
  if(store.getToken()){
    config.headers.Authorization = store.getToken()
  }
  return config
}, error => Promise.reject(error))

// 响应拦截器
instance.interceptors.response.use((response:AxiosResponse)=>{
  // 响应成功做什么
  // 判断code码
  const res = response.data
  if(res.code === 10000){
    return response.data.data // 返回正常的数据（id，name...）
  }
  // 不是就提示报错信息
  ElMessage.error(res.msg)
  
},(error:AxiosError) => {
  // 单独判断一下token失效
  if(error.status  === 401){
    // 删除token
   const store = usetoken()
   store.removeToken()
   router.push('/login')
  }else{
    const res = error.response?.data as ResponseResult
    ElMessage.error(res.msg)
  }
  return  Promise.reject(error)
})

// 封装导出class类
export class RequestAxios{
  static get<T>(url:string,params?:object){
    return instance.get<null,T>(url,{ params })
  }
  static post<T>(url:string,data?:object){
    return instance.post<null,T>(url,data)
  }
  static put<T>(url:string,data?:object){
    return instance.put<null,T>(url,data)
  }
  static delete<T>(url:string,params?:object){
    return instance.delete<null,T>(url,{ params })
  }
}